package com.mq.consumer.simple;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;

/**
 * @Classname KafkaSimpleConsumer
 * @Description
 * @Version 1.0.0
 * @Date 2024/12/4 17:15
 * @Created by ncs
 */
public class KafkaSimpleConsumerAutoOffSet {

    public static void main(String[] args) {
        //1. 创建消费者对象  需要范型 k,v
        // 1.1 配置对象
        HashMap<String, Object> configMap = new HashMap<>();
        configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.125.100:9093");
        // 1.2 序列化
        configMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        configMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //不启用默认提交 默认每五秒提交一次 可能会导致重复消费
        configMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        //从头开始消费
        configMap.put(ConsumerConfig.GROUP_ID_CONFIG, "czp3");
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(configMap);
        //2. 订阅主题
        kafkaConsumer.subscribe(Collections.singleton("czp_topic"));
        //3. 拉取数据
        while (true){
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100));
            records.forEach(item->{
                System.out.println(item);
            });
            //手动提交偏移量
            //异步提交
//            kafkaConsumer.commitAsync();
//            //同步提交
//            kafkaConsumer.commitSync();
        }
        // 4. 关闭连接
       // kafkaConsumer.close();
    }
}
